define(["utils", "base", '../libs/setRangeAvatar'], function (utils, baseClass, setRangeAvatar) {
    window.setRangeAvatar = setRangeAvatar;
    function avatar(url) {
        return url ? url + '.thumb.jpg' : '#';
    }

    var Component = function (config) {
        var _this = this;
        Component.baseConstructor.call(this, config);

        var rootDepartArr = [],
            rootPersonArr =[],
            rootTeamArr = []

        config.range && config.range.forEach(function(e) {
            switch(+e.dataType) {
                case 1:
                    rootDepartArr.push(e);
                    break;
                case 4:
                    rootPersonArr.push(e);
                    break;
                case 3:
                    rootTeamArr.push(e);
                    break;
            }
        })

        this.initRootDepart(rootDepartArr);

        this.initRootTeam(rootTeamArr);

        this.initRootPersonWrap(rootPersonArr);

        this.bindUnfoldEvent();
    }
    utils.extendClass(Component, baseClass);


    function unfolditemtpl(data) {
        return [
            '<div class="dc-rangetree-unfolditem" data-type="', data.type || 'depart', '" data-id="', data.deptId || data.teamId,'">',
                '<div class="dc-rangetree-unfoldtitle">',
                    '<div class="dc-rangetree-triangle"></div>',
                    '<span>', data.deptName || data.teamName, '</span>',
                '</div>',
            '</div>'
        ].join('');
    }

    function persontpl(data) {
        return [
            '<div class="dc-rangetree-personitem">',
                '<img src="', avatar(data.headImgUrl || data.avatar),'" onError="setRangeAvatar(this, \''+ data.userName +'\')">',
                '<span>', data.userName || data.name, '</span>',
            '</div>'
        ].join('');
    }

    Component.prototype.initRootDepart = function(arr){
        if(!arr.length) return;

        var res = arr.map(unfolditemtpl).join('');
        this.$el.append(res);
    };
    Component.prototype.initRootTeam = function(arr) {
        if(!arr.length) return;

        var res = arr.map(function(e) {
            e.type = 'team';
            return unfolditemtpl(e);
        }).join('');
        this.$el.append(res);
    }
    Component.prototype.initRootPersonWrap = function(arr){
        if(!arr.length) return;
        var hasDict={};
        var newArr = [];
        for(var i=0,j=arr.length;i<j;i++){
          var userId = arr[i].userId.toString();
          if(!hasDict[userId]){
            newArr.push(arr[i]);
            hasDict[userId] = true;
          }
        }
        var res = newArr.map(persontpl).join('');
        var $personbox = $("<div class='dc-rangetree-personbox clearfix'></div>").html(res);
        this.$el.append($personbox);
    };
    Component.prototype.bindUnfoldEvent = function() {
        var self = this;
        this.$el.off('click').on('click', '.dc-rangetree-personitem, .dc-rangetree-unfoldgrp, .dc-rangetree-persongrp', function(e) {
            e.stopPropagation();
        })
        .on('click', '.dc-rangetree-unfolditem', function(e) {
            e.stopPropagation();
            var $unfolditem = $(e.target).closest('.dc-rangetree-unfolditem');
            var unfolditem = $unfolditem[0];
            var type = $unfolditem.attr('data-type');
            var id = $unfolditem.attr('data-id');
            if( !$unfolditem.hasClass('active') ) {
                $unfolditem.addClass('active');

                if( unfolditem.initialed ) return;
                unfolditem.initialed = true;


                if( type === 'team' ) {
                    self.pageview.ajax({
                        type: 'GET',
                        url: '/group/member/' + id,
                        data: {},
                        success: function(res) {
                            var users = res.data;
                            if(users.length === 0) {
                                $unfolditem.addClass('null');
                            } else {
                                var $unfoldGrp = $('<div class="dc-rangetree-unfoldgrp"></div>');
                                var userHtml = users.map(persontpl).join('');
                                if(userHtml) {
                                    userHtml = '<div class="dc-rangetree-persongrp clearfix">'+ userHtml +'</div>';
                                }
                                $unfoldGrp.html(userHtml).appendTo($unfolditem);
                            }
                        }
                    })
                } else if( type === 'depart' ) {
                    self.pageview.ajax({
                        type: 'GET',
                        url: '/team/getDept',
                        data: {
                            id: id
                        },
                        success: function (res) {
                            if (res.code === 0) {
                                var departs = res.data.children;
                                var users = res.data.users;

                                if( departs.length === 0 && users.length === 0) {
                                    $unfolditem.addClass('null');
                                } else {
                                    var $unfoldGrp = $('<div class="dc-rangetree-unfoldgrp"></div>');

                                    var departHtml = departs.map(unfolditemtpl).join('');

                                    var userHtml = users.map(persontpl).join('');

                                    if(userHtml) {
                                        userHtml = '<div class="dc-rangetree-persongrp clearfix">'+ userHtml +'</div>';
                                    }

                                    $unfoldGrp.html(departHtml + userHtml).appendTo($unfolditem);
                                }
                            }
                        }
                    });
                }
            } else {
                $unfolditem.removeClass('active');
            }
        })
    }
    return Component;
});
